package org.groovymud.object.registry.cloneutils;

import java.util.List;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
/**
 * hook into the xstream marshaller to return the mud instances of certain objects that might 
 * be persisted instead of marshalling and unmarshalling them 
 * @author corbym
 *
 */
public class CloneConverter implements Converter {

	private List<Object> objects;

	public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
		// do not do anything
	}

	public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
		Object instance = null;

		instance = findInstance(context.getRequiredType());
		return instance;
	}

	private Object findInstance(Class type) {
		Object instance = null;
		for (Object obj : objects) {
			if (obj.getClass().equals(type)) {
				instance = obj;
				break;
			}
		}
		return instance;
	}

	public boolean canConvert(Class type) {
		return findInstance(type) != null;
	}

	/**
	 * @return the objects
	 */
	public List<Object> getObjects() {
		return objects;
	}

	/**
	 * @param objects the objects to set
	 */
	public void setObjects(List<Object> objects) {
		this.objects = objects;
	}

}
